package sample.androidwidget;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.simen.absadapter.AbsAdapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent();
        List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        Log.d("onCreate: ", "onCreate: " + resolveInfos.size());

        List<ExampleActivity> list = new ArrayList<>();
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES);
            ActivityInfo[] activityInfos = packageInfo.activities;
            Intent launchIntent = getPackageManager().getLaunchIntentForPackage(getPackageName());
            if (activityInfos != null && activityInfos.length > 0) {
                for (ActivityInfo info : activityInfos) {
                    if (info.name.equals(launchIntent.getComponent().getClassName())) {
                        continue;
                    }
                    list.add(new ExampleActivity(this, info));
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return;
        }

        setListAdapter(new AbsAdapter<ExampleActivity>(this, list, R.layout.adapter_item) {
            @Override
            protected boolean onItemAdapter(AbsViewHolder viewHolder, ExampleActivity element, int position) {
                viewHolder.setTextOrButton(R.id.example, element.name);
                return false;
            }
        });
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        ExampleActivity example = (ExampleActivity) v.getTag(R.id.absadapter_id);
        Intent intent = null;
        try {
            intent = new Intent(this, Class.forName(example.className));
            startActivity(intent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    class ExampleActivity {
        public String name;
        public String className;

        public ExampleActivity(Context context, ActivityInfo info) {
            this.name = context.getString(info.descriptionRes);
            this.className = info.name;
        }
    }
}
